package com.cy.store.service.impl;

import com.cy.store.domain.Address;
import com.cy.store.domain.Order;
import com.cy.store.domain.OrderItem;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.service.*;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/3/2 18:22
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartVOService cartService;
    @Autowired
    private IUserService userService;
     @Override
    public Order createOrder(Integer aid, Integer[] cids, Integer uid, String username) {
        List<CartVO> list = cartService.getOVByCids(uid, cids);
        Long totalPrice = 0L;
        for (CartVO cartVO : list) {
            totalPrice += cartVO.getRealPrice() * cartVO.getNum();
        }
        Address address = addressService.getByAid(aid, uid);
        Order order = new Order();
        //封装收货地址
        order.setUid(uid);
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        //封装订单数据
        order.setTotalPrice(totalPrice);
        order.setOrderTime(new Date());
        order.setStatus(0);
        //封装四个日志
         order.setCreatedTime(new Date());
         order.setCreatedUser(username);
         order.setModifiedTime(new Date());
         order.setModifiedUser(username);

         //插入订单数据
         int rows = orderMapper.insertOrder(order);
         if(rows!=1){
             throw new InsertException("插入订单数据时产生未知的异常");
         }
         //插入订单项数据
         for (CartVO cartVO : list) {
             OrderItem orderItem = new OrderItem();
             //封装订单项数据
             orderItem.setOid(order.getOid());
             orderItem.setPid(cartVO.getPid());
             orderItem.setTitle(cartVO.getTitle());
             orderItem.setImage(cartVO.getImage());
             orderItem.setPrice(cartVO.getRealPrice());
             orderItem.setNum(cartVO.getNum());
//             封装四个日志
             orderItem.setCreatedTime(new Date());
             orderItem.setCreatedUser(username);
             orderItem.setModifiedTime(new Date());
             orderItem.setModifiedUser(username);
             rows = orderMapper.insertOrderItem(orderItem);
             if(rows!=1){
                 throw new InsertException("插入订单项数据时产生未知的异常");
             }
//             这里添加删除购物车数据

         }
         return order;
    }
}
